package com.zw.cloud.mybatis.plus.service.impl.stenter;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.zw.cloud.mybatis.plus.entity.stenter.BaseDictionary;
import com.zw.cloud.mybatis.plus.mapper.stenter.BaseDictionaryMapper;
import com.zw.cloud.mybatis.plus.service.api.stenter.IBaseDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 公共字典表 服务实现类
 * </p>
 *
 * @author zw
 * @since 2023-11-30
 */
@Service
public class BaseDictionaryServiceImpl extends ServiceImpl<BaseDictionaryMapper, BaseDictionary> implements IBaseDictionaryService {

    @Override
    public List<Tree<String>> treeList(String groupCode) {
        LambdaQueryWrapper<BaseDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseDictionary::getGroupCode,groupCode);
        List<BaseDictionary> dictionaryList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(dictionaryList)) {
            return Lists.newArrayList();
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("code");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setParentIdKey("parentCode");
        treeNodeConfig.setChildrenKey("childrenList");
        treeNodeConfig.setWeightKey("usageCount");
        treeNodeConfig.setDeep(3);

        // rootId: "0"
        return TreeUtil.build(dictionaryList, "0", treeNodeConfig, (dictionary, treeNode) -> {
            // 赋值
            treeNode.setId(dictionary.getCode());
            treeNode.setParentId(dictionary.getParentCode());
            treeNode.setName(dictionary.getName());
            // 额外赋值
            treeNode.putExtra("actId", dictionary.getId());
            treeNode.putExtra("assistantsCode", dictionary.getAssistantsCode());
            treeNode.putExtra("isSupportDelivery", dictionary.getIsSupportDelivery());
            treeNode.putExtra("externalFiled", dictionary.getExternalFiled());
            treeNode.putExtra("usageCount", dictionary.getUsageCount());
            treeNode.putExtra("groupCode", dictionary.getGroupCode());

        });

    }
}
